package com.example.demo.conf;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author yujie
 * @create 2018-05-24 下午12:24
 **/
public class MyServletRequest extends HttpServletRequestWrapper {

    private final Map<String, String[]> params = new HashMap<>();

    public MyServletRequest(HttpServletRequest request) {
        super(request);

        try {
            ServletInputStream is = request.getInputStream();
            int len;
            byte[] bytes = new byte[128 * 1024];
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            while ((len = is.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, len);
            }
            String content = new String(byteArrayOutputStream.toByteArray(), "utf-8");
            System.out.println(content);
            Map<String, Object> map = new ObjectMapper().readValue(content, Map.class);
            map.entrySet().stream().forEach(entry -> {
                if (entry.getValue() != null) {
                    this.params.put(entry.getKey(), new String[]{entry.getValue().toString()});
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.params.putAll(request.getParameterMap());
    }


    @Override
    public String getParameter(String name) {
        return this.params.get(name)[0];
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        return this.params;
    }

    @Override
    public Enumeration<String> getParameterNames() {
        //return Iterators.asEnumeration(this.params.keySet().iterator());
        Iterator<String> itr = this.params.keySet().iterator();
        return new Enumeration<String>() {
            @Override
            public boolean hasMoreElements() {
                return itr.hasNext();
            }

            @Override
            public String nextElement() {
                return itr.next();
            }
        };
    }

    @Override
    public String[] getParameterValues(String name) {
        return this.params.get(name);
    }
}
